/**
 * 布尔开关类
 */
package example.hayukleung.recorder;

import java.lang.ref.WeakReference;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

/**
 * 布尔开关类
 * 
 * @author HayukLeung
 * 
 */
public class BoolListener implements OnClickListener, BoolInterface
{
	private static final String TAG = "BoolListener";
	private static final boolean ON = true;
	private static final boolean OFF = false;

	private boolean state = OFF;

	private BoolHandler handler = new BoolHandler(this);
	
	static class BoolHandler extends Handler
	{
		WeakReference<BoolListener> mBoolListener;
		
		public BoolHandler(BoolListener boolListener)
    {
	    this.mBoolListener = new WeakReference<BoolListener>(boolListener);
    }
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			BoolListener boolListener = mBoolListener.get();
			switch (msg.what)
			{
			case 0:
				boolListener.onceON();
				break;
			case 1:
				boolListener.onceOFF();
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	public void onClick(View v)
	{
		switchState();
		if (state)
		{
			if (!BoolListener.this.doON())
			{
				switchState();
			}
		}
		else
		{
			if (!BoolListener.this.doOFF())
			{
				switchState();
			}
		}
	}

	

	public boolean getState()
	{
		Message message = new Message();
		message.what = state ? 0 : 1;
		handler.sendMessage(message);
		Log.d(TAG, "getState = " + state);
		return state;
	}

	public void switchState()
	{
		Message message = new Message();
		message.what = (state = !state) ? 0 : 1;
		handler.sendMessage(message);
		Log.d(TAG, "switchState from " + !state + " to " + state);
	}

	@Override
  public synchronized boolean doON()
  {
		return true;
  }

	@Override
  public synchronized boolean doOFF()
  {
		return true;
  }

	@Override
  public synchronized void onceON()
  {
  }

	@Override
  public synchronized void onceOFF()
  {
  }
	
}
